import axios from 'axios'
import setting from '../setting'
import {Message} from "element-ui";


axios.defaults.baseURL = setting.BaseUrl
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  config.headers.Authorization = window.localStorage.getItem('token')|| ''
  // 在发送请求之前做些什么
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})
// 请求
const http = axios.create({
  baseURL: setting.BaseUrl,
  timeout: 6000
})

// 请求拦截
http.interceptors.request.use(config => {
  //请求头设置
  let token = window.localStorage.getItem('token') || ''
  config.headers.Authorization = 'Bearer '+token
  return config
}, err => {
  console.log(err);
})

// 响应拦截
http.interceptors.response.use(arr => {

  // 对响应码的处理
  switch (arr.status) {

    case 200:
      // Message({
      //   message: '成功',
      //   type: "success"
      // });
      break;
    case 201:
      Message({
        message: '添加成功',
        type: "success"
      });
      break;
    case 204:
      Message({
        message: '删除成功',
        type: "success"
      });
      break;
    case 400:
      Message({
        message: '错误请求',
        type: "warning"
      });
      break;
    case 401:
      console.log(401)
      Message({
        message: '未授权',
        type: "warning"
      });
      break;
    case 403:
      Message({
        message: '服务器拒绝服务',
        type: "error"
      });
      break;
    case 404:
      Message({
        message: '未找到相关信息',
        type: "warning"
      });
      break;
    case 500:
      Message({
        message: '服务器错误',
        type: "error"
      });
      break;
  }
  return arr.data
}, err => {

  console.log(err.response.status)
  if (err.response.status===401){
    alert("请登录")
    console.log(window.location.href)
     window.location.href = window.location.href+'login';
  }
})
// 返出
export default http
